import machine,time
from machine import Pin
class URM09_Trig:
    def __init__(self,trigger_pin,echo_timeout_us=500*2*30):
        pin = trigger_pin
        self.pin = Pin(pin, mode=Pin.OUT, pull=None)
        self.pin.value(0)
        self.echo_timeout_us = echo_timeout_us
        self.__limit = 500
    def _send_pulse_and_wait(self):
        self.pin.init(Pin.OUT)  # Ensure pin is output
        self.pin.value(0)
        time.sleep_us(5)
        self.pin.value(1)
        time.sleep_us(10)
        self.pin.value(0)
        
        self.pin.init(Pin.IN)  # Change pin to input
        pulse_time = machine.time_pulse_us(self.pin, 1, self.echo_timeout_us)
        return pulse_time
    def distance_mm(self):
        """
        Get the distance in milimeters without floating point operations.
        """
        pulse_time = self._send_pulse_and_wait()

        # To calculate the distance we get the pulse_time and divide it by 2 
        # (the pulse walk the distance twice) and by 29.1 becasue
        # the sound speed on air (343.2 m/s), that It's equivalent to
        # 0.34320 mm/us that is 1mm each 2.91us
        # pulse_time // 2 // 2.91 -> pulse_time // 5.82 -> pulse_time * 100 // 582 
        if pulse_time != (-1 or -2):
            mm = pulse_time * 100 // 582
            return mm
        else:
            return self.__limit*10

    def distance_cm(self):
        """
        Get the distance in centimeters with floating point operations.
        It returns a float
        """
        pulse_time = self._send_pulse_and_wait()

        # To calculate the distance we get the pulse_time and divide it by 2 
        # (the pulse walk the distance twice) and by 29.1 becasue
        # the sound speed on air (343.2 m/s), that It's equivalent to
        # 0.034320 cm/us that is 1cm each 29.1us
        if pulse_time != (-1 or -2):
            cms = (pulse_time / 2) / 29.1
            return round(cms,2)
        else:
            return self.__limit

